package org.visionlibrary.image.filters.bluring;

import java.awt.Point;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.WindowFilter;


public class LeeLocalStatistics extends WindowFilter {
	protected int width = 3;
	protected int height = 3;
	protected int variance = 2500;

	public LeeLocalStatistics(int size, int variance) {
		this(size, size, variance);
	}
	
	public LeeLocalStatistics(int width, int height, int variance) {
		this.width = width;
		this.height = height;
		this.variance = variance;
	}

	@Override
	protected int getNewPixelVal(TiledImage src, Point p, int channel) {
		Point pIter = new Point();
		int sum = 0;
		int n = 0;
		for (pIter.y = 0; pIter.y < windowHeight; pIter.y++)
			for (pIter.x = 0; pIter.x < windowWidth; pIter.x++) {
				int val = getWindowPixelVal(src, pIter, channel);
				sum += val;
				n++;
			}

		int mean = sum / n;

		pIter = new Point();
		int sumv = 0;
		for (pIter.y = 0; pIter.y < windowHeight; pIter.y++)
			for (pIter.x = 0; pIter.x < windowWidth; pIter.x++) {
				int val = getWindowPixelVal(src, pIter, channel);
				sumv += (val - mean) * (val - mean);
			}

		double v = sumv / (n - 1);
		
		int betha = (int) Math.max(
				Math.ceil((v - variance) / v), 0);

		int centerpixelval = getWindowPixelVal(src, this.dstPointInWindow,
				channel);

		//System.out.print(Math.ceil((variance - variancen) / variance));
		//System.out.println(" " + betha);

		return (betha * centerpixelval) + ((1 - betha) * mean);
	}

	@Override
	protected void setWindowProperties() {
		windowWidth = width;
		windowHeight = height;
		dstPointInWindow = new Point(width / 2, height / 2);
	}
}
